<template>
  <el-upload
    ref="upload"
    class="uploadVideo"
    :action="action"
    :limit="1"
    :on-exceed="handleExceed"
    :on-remove="handleRemove"
    :on-success="handleSuccess"
    :auto-upload="false"
  >
    <template #trigger>
      <el-button type="primary">选择视频</el-button>
    </template>
    <el-button class="ml-3" type="success" @click="submitUpload">
      上传到服务器
    </el-button>
    <template #tip>
      <div class="el-upload__tip text-red">
        选择一个视频文件, 新的视频文件会覆盖之前的视频文件
      </div>
    </template>
  </el-upload>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { genFileId } from "element-plus";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { videoBeforeUpload } from "@bis/utils/upload";
import { getBaseUrl } from "@bis/utils/constants";

const upload = ref<UploadInstance>();
const filePath = ref<string>("");
const action = ref<string>(getBaseUrl() + "/upload");

const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};

const handleRemove = () => {
  if (filePath.value) {
    console.log("需要删除");
  }
};

const handleSuccess = (res: any) => {
  filePath.value = res.data.filePath;
};

const submitUpload = () => {
  upload.value!.submit();
};

defineExpose({
  filePath,
});
</script>
